package com.gitee.leijin.rbac.security.handler;

import cn.hutool.cache.Cache;
import cn.hutool.json.JSONUtil;
import com.gitee.leijin.rbac.model.LoginResultDTO;
import com.gitee.leijin.rbac.model.TokenDTO;
import com.gitee.leijin.rbac.security.SecurityUser;
import com.gitee.leijin.rbac.service.CacheManager;
import com.gitee.leijin.rbac.util.AjaxUtils;
import com.gitee.leijin.rbac.util.JwtUtils;
import com.gitee.leijin.rbac.util.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Component
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private CacheManager cacheManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUser) {
            SecurityUser securityUser = (SecurityUser) principal;
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setUserId(securityUser.getSysUser().getUserId());
            tokenDTO.setUserName(securityUser.getUsername());
            tokenDTO.setAvatar(securityUser.getSysUser().getAvatar());

            // 生成JWT token
            String token = JwtUtils.getToken(tokenDTO);

            // 缓存信息到redis
            cacheManager.set(String.valueOf(tokenDTO.getUserId()), securityUser, 24, TimeUnit.HOURS);

            LoginResultDTO loginResultDTO = new LoginResultDTO();
            loginResultDTO.setToken(token);
            loginResultDTO.setAuthorizedUris(securityUser.getAuthorizedUris());
            AjaxUtils.response(response, JSONUtil.toJsonStr(Result.success(loginResultDTO)));
        }

    }
}
